import sqlite3


class User_DB:
    """
    管理用户信息数据库
    """

    def __init__(self):
        """
        初始化数据库以及建表
        """
        try:
            self.user_db_path = "./server/user_info.db"
            self.conn = sqlite3.connect(self.user_db_path)
            print("-----database connected-----")
            c = self.conn.cursor()
            c.execute("""
            CREATE TABLE IF NOT EXISTS user_info(
                user_name TEXT PRIMARY KEY NOT NULL, 
                MD5 TEXT NOT NULL
            );
            """)
            print("-----table user_info initialized-----")
            self.conn.commit()
            self.conn.close()
        except Exception as e:
            print(f"-----database error, {e}-----")

    def exeNonQuery(self, command: str):
        """
        执行非查询语句：insert, replace
        :param command: 查询语句
        :return:
        """
        try:
            conn = sqlite3.connect(self.user_db_path)
            c = conn.cursor()
            c.execute(command)
            conn.commit()
            print("------table modified success-----")
            conn.close()
        except Exception as e:
            print(f"-----database error, {e}-----")

    def exeQuery(self, command: str):
        """
        查询语句
        :param command:
        :return:list[[]]类型，一行结果为一个列表
        """
        try:
            conn = sqlite3.connect(self.user_db_path)
            c = conn.cursor()
            c.execute(command)
            res = c.fetchall()
            print("------query succeed-----")
            conn.close()
            return res
        except Exception as e:
            print(f"-----database error, {e}-----")

